package com.ruoyi.system.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.mapper.ResidentInfoMapper;
import com.ruoyi.system.mapper.SysDeptMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.MarketingBusinessMapper;
import com.ruoyi.system.domain.MarketingBusiness;
import com.ruoyi.system.service.IMarketingBusinessService;

/**
 * 营销业务办理Service业务层处理
 *
 * @author Alex
 * @date 2025-07-16
 */
@Service
public class MarketingBusinessServiceImpl implements IMarketingBusinessService
{
    @Autowired
    private MarketingBusinessMapper marketingBusinessMapper;
    @Autowired
    private SysDeptMapper sysDeptMapper;
    @Autowired
    private ResidentInfoMapper residentInfoMapper;

    /**
     * 查询营销业务办理
     *
     * @param id 营销业务办理主键
     * @return 营销业务办理
     */
    @Override
    public MarketingBusiness selectMarketingBusinessById(Long id)
    {
        return marketingBusinessMapper.selectMarketingBusinessById(id);
    }

    /**
     * 查询营销业务办理列表
     *
     * @param marketingBusiness 营销业务办理
     * @return 营销业务办理
     */
    @Override
    public List<MarketingBusiness> selectMarketingBusinessList(MarketingBusiness marketingBusiness)
    {
        return marketingBusinessMapper.selectMarketingBusinessList(marketingBusiness);
    }

    /**
     * 新增营销业务办理
     *
     * @param marketingBusiness 营销业务办理
     * @return 结果
     */
    @Override
    public int insertMarketingBusiness(MarketingBusiness marketingBusiness)
    {
        marketingBusiness.setCreateTime(DateUtils.getNowDate());
        return marketingBusinessMapper.insertMarketingBusiness(marketingBusiness);
    }

    /**
     * 修改营销业务办理
     *
     * @param marketingBusiness 营销业务办理
     * @return 结果
     */
    @Override
    public int updateMarketingBusiness(MarketingBusiness marketingBusiness)
    {
        marketingBusiness.setUpdateTime(DateUtils.getNowDate());
        return marketingBusinessMapper.updateMarketingBusiness(marketingBusiness);
    }

    /**
     * 批量删除营销业务办理
     *
     * @param ids 需要删除的营销业务办理主键
     * @return 结果
     */
    @Override
    public int deleteMarketingBusinessByIds(Long[] ids)
    {
        return marketingBusinessMapper.deleteMarketingBusinessByIds(ids);
    }

    /**
     * 删除营销业务办理信息
     *
     * @param id 营销业务办理主键
     * @return 结果
     */
    @Override
    public int deleteMarketingBusinessById(Long id)
    {
        return marketingBusinessMapper.deleteMarketingBusinessById(id);
    }

    @Override
    public List<Map<String, Object>> countPackageType(Long deptId, Long marketingUserId, String startDate, String endDate) {
        return marketingBusinessMapper.countPackageType(deptId, marketingUserId, startDate, endDate);
    }

    /**
     * 根据套餐类型统计各营业部下套餐数量，返回dept_id和dept_name
     */
    @Override
    public List<Map<String, Object>> countByPackageTypeAndDept(
        String packageType,
        String effectiveDate,
        String expireDate,
        Long deptId
    ) {
        List<Map<String, Object>> resultList = new ArrayList<>();
        //查询直属子部门
        List<SysDept> sysDepts = sysDeptMapper.selectDirectChildrenByParentId(deptId);

        for (SysDept sysDept : sysDepts){
            Long currentDeptId = sysDept.getDeptId();
            List<SysDept> list = sysDeptMapper.selectDirectChildrenByParentId(currentDeptId);
            List<Long> deptIdList = list.stream()
                    .map(SysDept::getDeptId)
                    .collect(Collectors.toList());
            int count = marketingBusinessMapper.countByDeptIdsAndPackageTypeAndDate(deptIdList, packageType, effectiveDate, expireDate);
            // 组装结果
            Map<String, Object> map = new HashMap<>();
            map.put("deptName", sysDept.getDeptName());
            map.put("deptId", sysDept.getDeptId());
            map.put("count", count);
            resultList.add(map);
        }
        return resultList;
    }

    @Override
    public List<Map<String, Object>> countByRanking(Long deptId, String effectiveDate, String expireDate) {
        // 获取所有子部门
        List<SysDept> sysDepts = sysDeptMapper.selectChildrenDeptById(deptId);
        List<Map<String, Object>> resultList = new ArrayList<>();
        for (SysDept sysDept : sysDepts) {
            Long currentDeptId = sysDept.getDeptId();
            String deptName = sysDept.getDeptName();
            // 目标值（email字段，假设为数字字符串）
            int target = 0;
            try {
                target = Integer.parseInt(sysDept.getEmail());
            } catch (Exception e) {
                target = 0;
            }
            // 实际值
            int actual = marketingBusinessMapper.countPackageType2ByDeptId(currentDeptId); // 你需要有这个方法
            // 完成率
            double percent = target == 0 ? 0.0 : ((double) actual / target) * 100;
            // 保留两位小数
            percent = Math.round(percent * 100.0) / 100.0;
            String returnPer = percent + "%";
            // 是否完成
            int finished = actual >= target && target > 0 ? 1 : 2;
            // 组装结果
            Map<String, Object> map = new HashMap<>();
            map.put("deptName", deptName);
            map.put("percent", returnPer);
            map.put("finished", finished);
            resultList.add(map);
        }
        return resultList;
    }

    @Override
    public List<Map<String, Object>> countByPermeability(Long deptId) {
        List<Map<String, Object>> resultList = new ArrayList<>();
        // 获取所有子部门
        List<SysDept> sysDepts = sysDeptMapper.selectDirectChildrenByParentId(deptId);
        for (SysDept sysDept : sysDepts) {
            Long dept = sysDept.getDeptId();
            List<SysDept> sysDeptsxq = sysDeptMapper.selectDirectChildrenByParentId(dept);
            List<Long> deptIdList = sysDeptsxq.stream()
                    .map(SysDept::getDeptId)
                    .collect(Collectors.toList());
            String deptName = sysDept.getDeptName();
            int total = residentInfoMapper.countByDeptId(dept); // 总住户数
            int actual = marketingBusinessMapper.countPackageType2ByDeptIds(deptIdList); // 实际办理宽带数
            double permeability = total == 0 ? 0.0 : ((double) actual / total) * 100;
            permeability = Math.round(permeability * 100.0) / 100.0; // 保留两位小数
            Map<String, Object> map = new HashMap<>();
            map.put("deptName", deptName);
            map.put("permeability", permeability);
            map.put("actual", actual);
            resultList.add(map);
        }
        return resultList;
    }
}
